package com.kvn.universal.exception;

import java.text.MessageFormat;

import org.apache.commons.lang3.ArrayUtils;

/**
 * 万用链 jar 中的异常。
 * 异常区段：1001-1099
 * @author wzy 2017-08-11
 */
public enum UniversalChainErrors implements IErrors {
	EMPTY_FILTER(1001, "filters is empty"),
	OTHER_THREAD_PROCESSING(1002, "幂等异常，其他线程正在操作"),
	RETURNCLASS_NOT_FOUND(1003, "幂等记录中的returnclass[{0}]不存在"),
	LOCK_ERROR(1004, "lock error"),
	DESERIALIZATION_FAIL(1005, "反序列化失败。idenpotentId={0}"),
	IDENPOTENT_ERROR(1006, "幂等异常"),
	;

	private int code;
	private String message;

	private UniversalChainErrors(int code, String message) {
		this.code = code;
		this.message = message;
	}


	@Override
	public UniversalException exp() {
		return this.expMsg(this.message);
	}

	@Override
	public UniversalException exp(Object... args) {
		return this.expMsg(this.message, null, args);
	}

	@Override
	public UniversalException exp(Throwable cause, Object... args) {
		return this.expMsg(this.message, cause, args);
	}

	@Override
	public UniversalException expMsg(String message, Object... args) {
		return this.expMsg(message, null, args);
	}

	@Override
	public UniversalException expMsg(String message, Throwable cause, Object... args) {
		String formatedMsg = message != null ? message : this.getMessage();
		if (ArrayUtils.isNotEmpty(args) && formatedMsg != null) {
			// 将 message 中的占位符替换
			formatedMsg = MessageFormat.format(formatedMsg, args);
		}
		return new UniversalException(this.getCode(), formatedMsg, cause, args);
	}

	public int getCode() {
		return code;
	}

	public String getMessage() {
		return message;
	}
	

}
